package com.hai.util;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.Socket;
import java.net.UnknownHostException;

import com.hai.qtalk.ChatActivity;
import com.hai.qtalk.FragmentTabs;

import android.annotation.SuppressLint;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;

public class ClientThread implements Runnable {

	// 定义向UI线程发送消息的Handler对象
	//private Handler handler;
	// 定义接收UI线程消息的Handler对象
	public Handler receiveHandler;
	// 该线程所处理的socket所对应的输入流
	BufferedReader br = null;
	OutputStream os = null;
	Thread readThread;
	private String split = "y9t";

	@SuppressLint("HandlerLeak")
	@Override
	public void run() {
		try {
			if (HttpUtil.socket == null)
				reNewSocket();
			//发送登陆消息给服务器
			os.write(("0" + split + HttpUtil.UNAME + split + HttpUtil.UID
					+ split + " " + split + " "+"\r\n").getBytes("utf-8"));

			// 启动一条子线程来读取服务器响应的数据
			readThread=new Thread() {
				@Override
				public void run() {
					String content = null;
					// 不断读取Socket输入流中的内容
					try {
						//System.out.println("开始读取服务器数据");
						while ((content = br.readLine()) != null) {
							// 每当读到来自服务器的数据之后，发送消息通知程序界面显示该数据
							//System.out.println("-----读取到服务器数据-----");
							String[] info = content.split(split, 0);
							String type = info[0];// 消息的类型，0表示登陆消息，1表示大厅消息，2表示私聊消息
							String UNAME = info[1];
							String UID = info[2];
							String TID = info[3];
							String con = info[4];
							System.out.println("收到info为" + type + ",用户" +UNAME+UID+"发给"+ TID+"，内容为"+info[4]);
							Message msg = new Message();
							msg.obj = UNAME + ": " + con;
							if (type.equals("1")) {
								msg.what = 0x567;
								FragmentTabs.handler.handleMessage(msg);
								
							} else if (type.equals("2")) {
								msg.what = 0x123;
								ChatActivity.handler.handleMessage(msg);
							}
						}
						
					} catch (Exception e) {
						System.out.println("读取服务器数据异常");
						reNewSocket();
						e.printStackTrace();
					}
				}
			};
			readThread.start();
			// 为当前线程初始化Looper
			Looper.prepare();
			// 创建receiveHandler对象
			receiveHandler = new Handler() {
				@Override
				public void handleMessage(Message msg) {
					// 接收到UI线程中用户输入的数据

					// 将用户在文本框内输入的内容写入网络
					try {
						if (null == HttpUtil.socket || HttpUtil.socket.isClosed()) {
							System.out.println("socket为空或已关闭");
							reNewSocket();
							os = HttpUtil.socket.getOutputStream();
							
						}
						
						if (msg.what == 0x345) {// 私聊消息
							String header = "2" + split + HttpUtil.UNAME
									+ split + HttpUtil.UID + split;
							os.write((header + msg.obj.toString() + "\r\n")
									.getBytes("utf-8"));
							// 发送出的消息的第一个字符，0表示登陆消息，1表示大厅消息，2表示私聊消息
						} else if (msg.what == 0x234) {// 大厅消息
							String header = "1" + split + HttpUtil.UNAME
									+ split + HttpUtil.UID + split;
							os.write((header + msg.obj.toString() + "\r\n")
									.getBytes("utf-8"));
						}
						else if(msg.what==0x111){
							os.write((msg.obj.toString() + "\r\n")
									.getBytes("utf-8"));
						}
						System.out.println("====发送msg:" + msg.obj + "====");
					} catch (Exception e) {
						System.out.println("发送异常");
						reNewSocket();
						e.printStackTrace();
					}

				}
			};
			// 启动Looper
			Looper.loop();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public void reNewSocket(){
		try {
			HttpUtil.socket =  new Socket(HttpUtil.SERVERIP,
					HttpUtil.SERVERPORT);
			br = new BufferedReader(new InputStreamReader(
					HttpUtil.socket.getInputStream(), "utf-8"));// 没加编码，被坑死
			os = HttpUtil.socket.getOutputStream();
			//readThread.start();
		} catch (UnknownHostException e) {
			System.out.println("居然new socket也异常111");
			e.printStackTrace();
		} catch (IOException e) {
			System.out.println("居然new socket也异常222");
			e.printStackTrace();
		}// 一个客户端只需要一个socket和服务器通信，由服务器转发即可
	}
	
}
